package com.software.myopiachildren.fragment;


import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleReadResponse;
import com.inuker.bluetooth.library.connect.response.BleUnnotifyResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.model.BleGattService;
import com.software.myopiachildren.App;
import com.software.myopiachildren.MainActivity;
import com.software.myopiachildren.R;
import com.software.myopiachildren.base.BaseFragment;
import com.software.myopiachildren.bean.BaseInfo;
import com.software.myopiachildren.content.Constant;
import com.software.myopiachildren.http.HostType;
import com.software.myopiachildren.http.HttpApi2;
import com.software.myopiachildren.receiver.BluetoothStateBroadcastReceive;
import com.software.myopiachildren.receiver.NotifyClickReceiver;
import com.software.myopiachildren.ui.BindDeviceActivity;
import com.software.myopiachildren.ui.DeviceListActivity;
import com.software.myopiachildren.ui.ScanBindActivity;
import com.software.myopiachildren.utils.ToastUtil;
import com.software.myopiachildren.utils.bluetooth.HexAndByte;
import com.software.myopiachildren.utils.eb.EB;
import com.software.myopiachildren.utils.eb.EbData;
import com.software.myopiachildren.utils.perm.NetworkUtils;
import com.software.myopiachildren.utils.sp.SP;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.greenrobot.eventbus.Subscribe;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.inuker.bluetooth.library.Code.REQUEST_SUCCESS;
import static com.inuker.bluetooth.library.Constants.STATUS_CONNECTED;
import static com.inuker.bluetooth.library.Constants.STATUS_DISCONNECTED;
import static com.inuker.bluetooth.library.utils.BluetoothUtils.registerReceiver;
import static com.inuker.bluetooth.library.utils.BluetoothUtils.unregisterReceiver;
import static com.software.myopiachildren.App.mBluetoothClient;

/**
 * @author penglei
 * @date 2020/05/13
 * 首页连接
 */
public class ConnectFragment extends BaseFragment {
    private static final String TAG = "ConnectFragment";

    @BindView(R.id.iv_title_left)
    ImageView mIvTitleLeft;
    @BindView(R.id.tv_title_text)
    TextView mTvTitleText;
    @BindView(R.id.tv_title_right)
    TextView mTvTitleRight;
    @BindView(R.id.lay_title_home)
    LinearLayout mLayTitleHome;

    @BindView(R.id.iv_conn_status)
    ImageView mIvConnStatus;
    @BindView(R.id.tv_conn_status)
    TextView mTvConnStatus;
    @BindView(R.id.btn_connect)
    Button mBtnConnect;


    private static final boolean D = true;
    private static final int REQUEST_CONNECT_DEVICE = 1;

    private BluetoothAdapter mBluetoothAdapter = null;  // 蓝牙适配器
    private String bluetoothMAC;
    private BleGattService bluetoothService;

    private int bluetoothStatus = 1;  // 1:未连接  2：已连接

    // 蓝牙连接状态监听
    private BluetoothStateBroadcastReceive mReceive;


    @Override
    protected int getContentViewId() {
        return R.layout.fragment_connect;
    }

    @Override
    public void initView() {
        EB.register(this);
        mIvTitleLeft.setVisibility(View.GONE);
        mTvTitleText.setText(getResources().getString(R.string.s_prevention_myopia));
        mTvTitleRight.setVisibility(View.VISIBLE);
        mTvTitleRight.setText(getResources().getString(R.string.s_search_bluetooth_device));

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        ensureDiscoverable(); // 判断蓝牙可被发现

        // 注册蓝牙监听
        registerBluetoothReceiver();
    }

    @Override
    public void initData() {
        autoConnect();
    }

    @OnClick({R.id.btn_connect, R.id.tv_title_right})
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.btn_connect:
//                getAlert();
//                getActivateDevice();

                if (bluetoothStatus == 2) {
                    closeConnect();
                } else if (bluetoothStatus == 1) {
                    autoConnect();
                }
                break;

            case R.id.tv_title_right:
                getPermissions();
                break;
        }
    }


    @Subscribe
    public void onEvent(EbData data) {
        if (data.getType() == 31) {
            // 状态栏手动关闭蓝牙
            int status = mBluetoothClient.getConnectStatus(bluetoothMAC);
            //  2：连接   1：连接中  3:断连中  0：断连  -1：未知
            if (status == 2) {
                closeConnect();
            }

        } else if (data.getType() == 32) {
            // 状态栏手动开启蓝牙

        } else if (data.getType() == 33) {
            // 设置蓝牙连接手动关闭蓝牙
            int status = mBluetoothClient.getConnectStatus(bluetoothMAC);
            //  2：连接   1：连接中  3:断连中  0：断连  -1：未知
            if (status == 2) {
                closeConnect();
            }
        } else if (data.getType() == 34) {
            //设置蓝牙连接手动开启蓝牙

        }
    }


    @Override
    public void onStart() {
        super.onStart();
        if (!mBluetoothAdapter.isEnabled()) { // 动态请求打开蓝牙
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivity(enableIntent);
        }
    }

    @Override
    public void onDestroy() {
        EB.unregister(this);
        super.onDestroy();
        mBluetoothClient.disconnect(bluetoothMAC);
        mBluetoothClient.unregisterConnectStatusListener(bluetoothMAC, mBleConnectStatusListener);

        // 注销蓝牙状态监听
        unregisterBluetoothReceiver();
    }

    /**
     * 注册蓝牙状态监听
     */
    private void registerBluetoothReceiver() {
        if (mReceive == null) {
            mReceive = new BluetoothStateBroadcastReceive();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
        intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");
        registerReceiver(mReceive, intentFilter);
    }

    /**
     * 注销蓝牙状态监听
     */
    private void unregisterBluetoothReceiver() {
        if (mReceive != null) {
            unregisterReceiver(mReceive);
            mReceive = null;
        }
    }


    // 确保本蓝牙可以被发现
    private void ensureDiscoverable() {
        Log.d("===", "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * 判断是否连接设备
     */
    private void isBluetoothConnect() {
        final String blMAC = new SP().load(Constant.BLUETOOTH_MAC, "");
        if (!TextUtils.isEmpty(blMAC)) {
            int status = mBluetoothClient.getConnectStatus(blMAC);
            Log.e(TAG, "=====主动获取连接状态status:" + status);
            //  2：连接   1：连接中  3:断连中  0：断连  -1：未知
            if (status == 0) {
                bluetoothStatus = 1;
                if (Util.isOnMainThread()) {
                    Glide.with(getActivity().getApplicationContext()).load(R.mipmap.ic_bluetooth_status_failure).into(mIvConnStatus);
                }
                mTvConnStatus.setText(getResources().getString(R.string.s_unconnect));
                mBtnConnect.setText(getResources().getString(R.string.s_connect));
            } else if (status == 2) {
                bluetoothStatus = 2;
                if (Util.isOnMainThread()) {
                    Glide.with(getActivity().getApplicationContext()).load(R.mipmap.ic_bluetooth_status_sussess).into(mIvConnStatus);
                }
                mTvConnStatus.setText(getResources().getString(R.string.s_onconnect));
                mBtnConnect.setText(getResources().getString(R.string.s_cancel_connect));
                setOpenNotify();
            }
        }
    }

    /**
     * 检测权限
     */
    private void getPermissions() {
        AndPermission.with(this)
                .permission(Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION)
                .onGranted(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Log.e(TAG, "权限通过");
                        //跳转扫描蓝牙设备界面
                        Intent intent = new Intent(getActivity(), DeviceListActivity.class);
                        startActivityForResult(intent, REQUEST_CONNECT_DEVICE);
                    }
                })
                .onDenied(new Action() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + getActivity().getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        ToastUtil.showShort("没有权限无法扫描出设备呦");
                    }
                }).start();
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (D)
            Log.e("===", "onActivityResult " + resultCode);
        Log.e("===", "555555555555");
        switch (requestCode) {
            case REQUEST_CONNECT_DEVICE:
                // When DeviceListActivity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    // Get the device MAC address
                    final String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    BleConnectOptions options = new BleConnectOptions.Builder()
                            .setConnectRetry(3)   // 连接如果失败重试3次
                            .setConnectTimeout(30000)   // 连接超时30s
                            .setServiceDiscoverRetry(3)  // 发现服务如果失败重试3次
                            .setServiceDiscoverTimeout(20000)  // 发现服务超时20s
                            .build();

                    // 连接蓝牙
                    mBluetoothClient.connect(address, options, new BleConnectResponse() {
                        @Override
                        public void onResponse(int code, BleGattProfile data) {
                            if (code == REQUEST_SUCCESS) {   // 连接成功
                                Log.e("===", " 连接成功:Connect Sucessfully");
                                // 断开上一次的连接
                                mBluetoothClient.disconnect(bluetoothMAC);
//                                mBluetoothClient.unregisterConnectStatusListener(bluetoothMAC, mBleConnectStatusListener);
                                // 添加蓝牙连接状态监听
//                                mBluetoothClient.registerConnectStatusListener(address, mBleConnectStatusListener);
                                bluetoothMAC = address;  // 保存已成功连接的地址
                                Log.e("===", "===" + bluetoothMAC);
                                new SP().save(Constant.BLUETOOTH_MAC, bluetoothMAC); // 保存蓝牙设备连接地址

                                List<BleGattService> services = data.getServices();
                                bluetoothService = services.get(2);
//                                setOpenNotify();
                                isBluetoothConnect();
                            } else {
                                Log.d(TAG, String.valueOf(code));
                            }
                        }
                    });
                }
                break;
        }
    }

    /**
     * 蓝牙连接状态监听变量
     */
    private final BleConnectStatusListener mBleConnectStatusListener = new BleConnectStatusListener() {
        @Override
        public void onConnectStatusChanged(String mac, int status) {
            Log.e(TAG, "===连接状态监听变量:" + status);
            if (status == STATUS_CONNECTED) {
                Log.e(TAG, "===STATUS_CONNECTED" + "已连接");
//                setOpenNotify();
            } else if (status == STATUS_DISCONNECTED) {
                Log.e(TAG, "===STATUS_DISCONNECTED" + "未连接");
            }

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    isBluetoothConnect();
                }
            });
        }
    };

    /**
     * 打开notify，获取连接发送数据
     */
    private void setOpenNotify() {
        Log.d(TAG, "Setup Chat Notify");
        Log.d(TAG, "000===" + bluetoothMAC);
        Log.d(TAG, "111===" + bluetoothService.getUUID());
        Log.d(TAG, "222===" + bluetoothService.getCharacters().get(0).getUuid());
        mBluetoothClient.notify(bluetoothMAC, bluetoothService.getUUID(),
                bluetoothService.getCharacters().get(0).getUuid(), new BleNotifyResponse() {
                    @Override
                    public void onNotify(UUID service, UUID character, byte[] value) {

//                        Log.e("111======", value + "");
//                        Log.e("222======", HexAndByte.bytesToCharArray(value) + "");
                        Log.e("333======", value.length + "");
                        for (int i = 0; i < value.length; i++) {
                            Log.e("444======", value[i] + "");
                        }

                        if (value.length == 2) {
                            Log.e("notify======","notify通知");
//                            showNotifictionIcon();
                            sendNotification();
                        }
                    }

                    @Override
                    public void onResponse(int code) {
                        Log.d(TAG, "====Notify-code:" + code);
                        if (code == REQUEST_SUCCESS) {
                            Log.d(TAG, "notify成功后:Open Notify Sucessfully");
                            // 打开notify成功后发送数据
                            // sendMessage(bluetoothMAC, bluetoothService, "AT");
                        }
                    }
                });
    }

    /**
     * /关闭notify，停止获取连接发送数据
     */
    private void setCloseNotify() {
        mBluetoothClient.unnotify(bluetoothMAC, bluetoothService.getUUID(),
                bluetoothService.getCharacters().get(0).getUuid(), new BleUnnotifyResponse() {
                    @Override
                    public void onResponse(int code) {
                        if (code == REQUEST_SUCCESS) {
                            // 关闭notify
                            Log.d(TAG, "===Close Notify Sucessfully");
                        }
                    }
                });
    }


    // 通过蓝牙接收数据
    private void readMessage() {
        mBluetoothClient.read(bluetoothMAC, bluetoothService.getUUID(),
                bluetoothService.getCharacters().get(0).getUuid(), new BleReadResponse() {
                    @Override
                    public void onResponse(int code, byte[] data) {
                        if (code == REQUEST_SUCCESS) {
                            String response = null;
                            try {
                                response = new String(data, "UTF-8");
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                            Log.e(TAG, "=====串口收到消息：" + response);
//                    mConversationArrayAdapter.add("Received: "+ response);
//                    mConversationArrayAdapter.notifyDataSetChanged();
                        }
                    }
                });
    }


    /**
     * 自动重连设备
     */
    private void autoConnect() {
        final String blMAC = new SP().load(Constant.BLUETOOTH_MAC, "");
        if (blMAC != null) {
            BleConnectOptions options = new BleConnectOptions.Builder()
                    .setConnectRetry(3)   // 连接如果失败重试3次
                    .setConnectTimeout(30000)   // 连接超时30s
                    .setServiceDiscoverRetry(3)  // 发现服务如果失败重试3次
                    .setServiceDiscoverTimeout(20000)  // 发现服务超时20s
                    .build();
            // 连接蓝牙
            mBluetoothClient.connect(blMAC, new BleConnectResponse() {
                @Override
                public void onResponse(int code, BleGattProfile data) {
                    if (code == REQUEST_SUCCESS) {   // 连接成功
                        Log.d("===", " 连接成功:Connect Sucessfully");
                        // 断开上一次的连接
                        mBluetoothClient.disconnect(bluetoothMAC);
//                        mBluetoothClient.unregisterConnectStatusListener(bluetoothMAC, mBleConnectStatusListener);
                        // 添加蓝牙连接状态监听
//                        mBluetoothClient.registerConnectStatusListener(blMAC, mBleConnectStatusListener);
                        bluetoothMAC = blMAC;  // 保存已成功连接的地址
                        Log.d("===", "===" + bluetoothMAC);
                        new SP().save("MAC", bluetoothMAC);
                        List<BleGattService> services = data.getServices();
                        bluetoothService = services.get(2);
//                        setOpenNotify();
                        isBluetoothConnect();
                    } else {
                        Log.d(TAG, String.valueOf(code));
                    }
                }
            });
        }
    }

    /**
     * 断开连接设备
     */
    private void closeConnect() {
        String blMAC = new SP().load(Constant.BLUETOOTH_MAC, "");
        Log.d("===", "===断开连接blMAC:" + blMAC);
        if (blMAC != null) {
            // 断开连接
            mBluetoothClient.disconnect(blMAC);
            mBluetoothClient.refreshCache(blMAC);
            mBluetoothClient.clearRequest(blMAC, 0);

            mBluetoothClient.registerConnectStatusListener(blMAC, mBleConnectStatusListener);
            setCloseNotify();
//            isBluetoothConnect();
        }
    }


    /**
     * 发送警报
     */
    private void getAlert() {
        String device_code = new SP().load(Constant.DEVICE_CODE, "");
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(getActivity())) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", device_code);
            params.put("type", 1 + "");

            HttpApi2.getApiService(HostType.TELE_CONFIG).getAlert(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }


    /**
     * 激活设备
     */
    private void getActivateDevice() {
        String device_code = new SP().load(Constant.DEVICE_CODE, "");
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(getActivity())) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("device_code", device_code);

            HttpApi2.getApiService(HostType.TELE_CONFIG).getActivateDevice(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<BaseInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(BaseInfo baseInfo) {
                            try {
                                Log.e(TAG, "===baseInfo:" + baseInfo.toString());
                                if (baseInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                } else {
                                    ToastUtil.showShort(baseInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }


    /**
     * 显示发送公告通知
     */
    public void showNotifictionIcon() {
        Log.e("notify======","notify999999");
        String title = "灵童宝贝通知";
        String content = "您当前使用手机距离太近，容易伤害眼睛，请保持距离，谢谢！";
        NotificationManager manager = (NotificationManager) App.getAppInstance().getSystemService(App.getContext().NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(App.getAppInstance());
        builder.setTicker("来自灵童宝贝的通知");//通知首次出现在通知栏，带上升动画效果的
        builder.setAutoCancel(true);//点击后消失
        builder.setSmallIcon(R.mipmap.ic_launcher);//设置通知栏消息标题的头像
        builder.setDefaults(NotificationCompat.DEFAULT_SOUND);//设置通知铃声
        builder.setContentTitle(title);//设置标题
        builder.setContentText(content);//设置内容
        builder.setPriority(Notification.PRIORITY_DEFAULT); //设置该通知优先级
        //利用PendingIntent来包装我们的intent对象,使其延迟跳转 设置通知栏点击意图
        builder.setContentIntent(createIntent(content));
        //  builder.setDeleteIntent(createDeleteIntent(json));
        manager.notify(1, builder.build());
        Log.e("notify======","notify888888");
    }

    /**
     * 创建点击事件的广播intent
     */
    public PendingIntent createIntent(String content) {
        Intent intent;
        PendingIntent contentIntent = null;
        Bundle mBundle = new Bundle();
        intent = new Intent();
        mBundle.putString("content", content);
        intent.putExtras(mBundle);
        intent.setClass(App.getContext(), NotifyClickReceiver.class);
        intent.setAction("com.software.myopiachildren.receiver.click.notify");

        contentIntent = PendingIntent.getBroadcast(App.getContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        return contentIntent;
    }



    private void sendNotification() {
        String id = "channel_001";
        String name = "name";
        NotificationManager notificationManager = (NotificationManager) App.getAppInstance().getSystemService(App.getContext().NOTIFICATION_SERVICE);
        Notification notification = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(App.getAppInstance())
                    .setChannelId(id)
                    .setContentTitle("灵童宝贝通知")
                    .setContentText("您当前使用手机距离太近，容易伤害眼睛，请保持距离，谢谢！")
                    .setDefaults(NotificationCompat.DEFAULT_SOUND)//设置通知铃声
                    .setSmallIcon(R.drawable.ic_launcher).build();
        } else {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(App.getAppInstance())
                    .setContentTitle("灵童宝贝通知")
                    .setContentText("您当前使用手机距离太近，容易伤害眼睛，请保持距离，谢谢！")
                    .setDefaults(NotificationCompat.DEFAULT_SOUND)//设置通知铃声
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setOngoing(true)
                    .setChannelId(id);//无效
            notification = notificationBuilder.build();
        }
        notificationManager.notify(1, notification);
    }




}
